<template>
  <div>
    <el-form v-model="formSearch" :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formSearch.content" placeholder="请输入角色名称"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-button type="primary" icon="el-icon-circle-plus-outline" @click="showAddRole" plain>新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="delBatch" plain>批量删除</el-button>
    </el-row>

    <el-table :data="roleList"
              v-loading="loading"
              style="width: 100%; margin-top: 20px"
              border
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column prop="id"
                       label="ID"
                       sortable
                       width="100">
      </el-table-column>
      <el-table-column prop="roleName"
                       label="角色名称"
                       width="180">
      </el-table-column>
      <el-table-column prop="roleKey"
                       label="权限字符">
      </el-table-column>
      <el-table-column prop="remark"
                       label="备注">
      </el-table-column>
      <el-table-column prop="status"
                       label="状态">
        <template slot-scope="scope">

          <el-dropdown  @command="updateStatus">
            <el-button style="border: none;outline: none;box-shadow:none;background: none">
              <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
              <el-tag v-if="scope.row.status === 2" type="info">停用</el-tag>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="handleUpdateStatus(scope.row.id, 1)">正常</el-dropdown-item>
              <el-dropdown-item :command="handleUpdateStatus(scope.row.id, 2)">停用</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEditRole(scope.row)" circle></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)" circle></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px"
        background
        :page-sizes="[5, 10]"
        layout="sizes, prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
    >
    </el-pagination>

    <!--新增角色-->
    <el-dialog title="新增角色" :visible.sync="addDialogFormVisible" width="600px">
      <el-form :model="addForm" :rules="rules">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off" style="width: 330px"></el-input>
        </el-form-item>
        <el-form-item label="角色权限字符" :label-width="formLabelWidth" prop="roleKey">
          <el-input v-model="addForm.roleKey" auto-complete="off" style="width: 330px"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="菜单权限" :label-width="formLabelWidth">
          <el-tree
              :props="fromProps"
              :data="addMenuTree"
              node-key="id"
              ref="tree"
              :default-checked-keys="[1]"
              show-checkbox>
          </el-tree>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="addForm.remark" auto-complete="off"
                    style="width: 330px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSure">确 定</el-button>
      </div>
    </el-dialog>

    <!--编辑角色-->
    <el-dialog title="新增角色" :visible.sync="editDialogFormVisible" width="600px">
      <el-form :model="editForm" :rules="rules">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editForm.roleName" auto-complete="off" style="width: 330px"></el-input>
        </el-form-item>
        <el-form-item label="角色权限字符" :label-width="formLabelWidth" prop="roleKey">
          <el-input v-model="editForm.roleKey" auto-complete="off" style="width: 330px"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="editForm.status" placeholder="1-在售 2-下架 ">
            <el-option label="正常" value="1"></el-option>
            <el-option label="停用" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="菜单权限" :label-width="formLabelWidth">
          <el-tree
              :props="fromProps"
              :data="editMenuTree"
              node-key="id"
              ref="tree"
              :check-strictly="checkStrictly"
              :default-checked-keys="editCheckedKeys"
              show-checkbox>
          </el-tree>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="editForm.remark" auto-complete="off"
                    style="width: 330px"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSure">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getMenuTree, getMenuTreeByRole} from "@/api/menu";

export default {
  name: "admin-role",
  data() {
    return {
      roleList: [],
      loading: true, //加载动画
      formSearch: { //搜索表单
        content: ''
      },
      pageSize: 5,
      total: 0,
      currentPage: 0,
      multipleSelection: [],
      formLabelWidth: '120px',
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      addForm: {},
      fromProps: {
        label: 'menuName',
        children: 'children'
      },
      addMenuTree: [], //菜单树形集合
      editForm: {},
      editMenuTree: [],
      editCheckedKeys: [], //根据角色获取到的权限菜单id集合
      checkStrictly: false, //控制tree树的优化显示
      rules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        roleKey: [
          {required: true, message: '请输入权限字符', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
      },
    }
  },
  mounted() {
    this.getRoleList()
  },

  methods: {
    getRoleList() {
      this.loading = true
      this.request.get('/role/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          content: this.formSearch.content
        }
      }).then((res) => {
        this.roleList = res.list
        this.total = Number(res.total)
        this.loading = false
      }).catch(e => {
        this.$message.error(e)
      })
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },

    //显示添加角色弹框
    showAddRole() {
      this.addDialogFormVisible = true
      this.addForm = {}
      getMenuTree().then((res) => {
        this.addMenuTree = res
      })
    },
    //添加角色确认
    handleAddSure() {
      this.addForm.menuIds = this.getMenuAllCheckedKeys()
      this.request.post('/role/add', this.addForm).then(() => {
        this.$message.success('添加成功')
        this.addDialogFormVisible = false
        this.getRoleList()
      }).catch(e => {
        this.$message.error(e)
      })
    },

    //显示编辑角色弹框
    showEditRole(row) {
      this.editDialogFormVisible = true
      this.request.get('/role/' + row.id).then((res) => {
        this.editForm = res
        this.editForm.status = res.status + ''
      })
      //根据角色id查询菜单树形
      getMenuTreeByRole(row.id).then((res) => {
        this.editMenuTree = res.menus
        //优化菜单树形结构的显示
        this.$nextTick(() => {
          const checkedKeys = res.checkedKeys
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.tree.setChecked(v, true, false)
            })
          })
        })


        // this.editCheckedKeys = res.checkedKeys
        //优化菜单树形结构的显示
/*        if (res.checkedKeys) {
          this.checkStrictly = true;  //赋值之前先设置为true
          this.$nextTick(() => {
            const routes = res.checkedKeys;
            this.$refs.tree.setCheckedKeys(routes) //给树节点赋值
            setTimeout(() => {
              this.checkStrictly = false //赋值完成后设置为false
            },1000)
          })
        }*/

      })
    },

    //编辑角色确认
    handleEditSure() {
      this.editForm.menuIds = this.getMenuAllCheckedKeys()
      this.request.put('/role/update', this.editForm).then(() => {
        this.$message.success('修改成功')
        this.editDialogFormVisible = false
        this.getRoleList()
      }).catch(e => {
        this.$message.error(e)
      })
    },

    //单个删除
    handleDelete(row) {
      this.$confirm("是否删除该角色", "提示", {
        type: 'error'
      }).then(() => {
        this.request.delete('/role/' + row.id).then(() => {
          this.$message.success("删除成功")
          this.getRoleList()
        }).catch(e => {
          this.$message.error(e)
        })
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },

    //改变单个分类的状态
    handleUpdateStatus(id, status) {
      return {
        id, status
      }
    },
    updateStatus(command) {
      let {id, status} = command
      this.request.put('/role/status/' + id + '/' + status).then(() => {
        this.$message.success('更新成功')
        this.getRoleList()
      }).catch(e => {
        this.$message.error(e)
      })
    },

    //批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delBatch() {
      this.$confirm("是否确认批量删除", "提示", {
        type: 'error'
      }).then(() => {
        let ids = this.multipleSelection.map(v => v.id);
        if (ids.length > 0) {
          this.request.delete('/role/' + ids).then(() => {
            this.$message.success('批量删除成功')
            location.reload()
          }).catch(e => {
            this.$message.error(e)
            location.reload()
          })
        } else {
          this.$message.info('当前未选中订单')
        }

      }).catch(() => {
        this.$message.info('取消删除')
      })
    },

    //搜索
    onSubmit() {
      this.getRoleList()
    },
    //分页功能
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getOrderList()
    },
    //翻页功能
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getOrderList()
    },
  }
}
</script>

<style scoped>

</style>